package com.example.service;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    Button btnBindService,btnUnbindService,btnGetStatus;
    TextView tvServiceStatus;
    MyService.MyServiceBinder serviceBinder;
    boolean isServiceBind=false;
    ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serviceBinder=(MyService.MyServiceBinder) service;
            Log.d("MainActivity","服务成功绑定.内存地址"+serviceBinder.toString());
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("MainActivity","服务成功断开.内存地址"+serviceBinder.toString());
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnBindService=findViewById(R.id.btn_bind);
        btnUnbindService=findViewById(R.id.btn_unbind);
        btnGetStatus=findViewById(R.id.btn_get);
        tvServiceStatus=findViewById(R.id.tv_service);
        btnBindService.setOnClickListener(this);
        btnUnbindService.setOnClickListener(this);
        btnGetStatus.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        Intent intent=new Intent();
        intent.setClass(MainActivity.this,MyService.class);
        switch (v.getId()){
            case R.id.btn_bind:
//如果 service 尚未绑定就绑定，如果已经绑定则忽略
                if(!isServiceBind){
                    bindService(intent,conn, Service.BIND_AUTO_CREATE);
                    isServiceBind=true;
                    tvServiceStatus.setText("服务已绑定");

                }
                break;
            case R.id.btn_get:
//如果 service 已经绑定，获取
                if(isServiceBind){
                    tvServiceStatus.setText("service的count计数："+serviceBinder.getCount());
                }
                break;
            case R.id.btn_unbind:
//如果 service 已经绑定，则可以解绑，否则忽略
                if(isServiceBind){
                    unbindService(conn);
                    isServiceBind=false;
                    tvServiceStatus.setText("服务已解绑");
                }
                break;
        }
    }
}
